package com.xiaoa.gossip.cluster.service.impl;

import com.xiaoa.gossip.cluster.command.CurrentNodeState;
import com.xiaoa.gossip.cluster.command.PingCommand;
import com.xiaoa.gossip.cluster.command.PingNodeState;
import com.xiaoa.gossip.cluster.service.ClusterMsgFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

import static com.xiaoa.gossip.cluster.command.NodeState.NODE_STATE_FAIL;
import static com.xiaoa.gossip.cluster.command.PingCommand.CLUSTERMSG_TYPE_FALL;

/**
 * @author luokaichuang
 * @time 2020/6/19
 */
@Service
public class ClusterMsgFactoryImpl implements ClusterMsgFactory {


    @Value("${gossip.version}")
    private Double version;

    @Autowired
    private CurrentNodeState currentNodeState;

    @Override
    public PingCommand createNodeFail(PingNodeState failNote) {

       try{
           PingCommand failCommand = createCurrentPing(CLUSTERMSG_TYPE_FALL);

           // 克隆节点，将节点状态设置为FAIL
           PingNodeState clonePingNote = new PingNodeState();
           BeanUtils.copyProperties(failNote , clonePingNote);
           clonePingNote.setState(NODE_STATE_FAIL);
           clonePingNote.setLastPingTime(new Date());

           failCommand.setPingNodeStateList(Arrays.asList(clonePingNote));
           return failCommand;

       }catch (Exception e){
           throw  new RuntimeException(e);
       }

    }


    /**
     * 创建ping对象 （当前系欸但信息）
     *
     * @author jm008783
     * @param: []
     * @return: com.xiaoa.gossip.cluster.command.PingCommand
     **/
    private PingCommand createCurrentPing(int type) {

        PingCommand pingCommand = new PingCommand();
        pingCommand.setVer(version);
        pingCommand.setId(currentNodeState.getId());
        pingCommand.setPort(currentNodeState.getPort());
        pingCommand.setCount(0);
        pingCommand.setType(type);
        pingCommand.setMyip(currentNodeState.getIp());
        pingCommand.setState(currentNodeState.getState());

        return pingCommand;
    }
}
